// xnt event interface
// Daly


#include "xnt_base.h"
#include "xnt_event.h"
#include "xnt_timer.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

void xnt_default_log(const char* msg);

#define CHECK_DRIVER_INIT if(!g_init) { \
	g_log("driver not ready yet"); \
	return; \
}

//global variable

int g_tick_interval = 100;
static int g_init = 0;


const char* g_log_path = ".";
const char* g_log_file = "xnt_info.log";
xnt_event_t g_ev_timer ;

xnt_logger_proc g_log = xnt_default_log;

int xnt_init(xnt_conf_t* cf)
{
    int ret;
	if (cf == NULL) return XNT_RET_ERR;
	g_tick_interval = cf->timetick;

	if (g_tick_interval <= 10) g_tick_interval = 10;
	else if (g_tick_interval > 10000) g_tick_interval = 10000;

	ret = g_event_drv->init(cf);
	if (ret != XNT_RET_OK) return ret;
	timer_table_init();
	//init ok
	g_init = 1;
	g_log("init event driver ok");
	
	return ret;
}

void xnt_add_event(xnt_event_t* ev, int fd, int ev_mask)
{
	int ret;
	CHECK_DRIVER_INIT
	if (fd < 0) return;
	ret = g_event_drv->ev_add(ev, fd, ev_mask);
}

void xnt_del_event(xnt_event_t* ev, int fd, int ev_mask)
{
	CHECK_DRIVER_INIT
	if (fd < 0) return;
	g_event_drv->ev_del(ev, fd, ev_mask);
}

void xnt_shutdown()
{
	g_event_drv->shutdown();
}

int xnt_process()
{
	int ret;
	int timepass, timeout;
	if(!g_init) return -2;

	xnt_timer_routine();
	timepass = xnt_get_timepass() % g_tick_interval;
	if (timepass > 0) {
		timeout = g_tick_interval - timepass; 
	} else {
		timeout = 20;
	}	
	timeout = timeout == 0 ? 1 : timeout;
	ret = g_event_drv->ev_process(timeout);
	if (ret == XNT_RET_ERR) {
		return -1;
	}
	return ret;
}

//default logger
//not thread safe
void xnt_default_log(const char* msg)
{
    FILE *fp = NULL;
    char path_buf[512];
    time_t tm;

    snprintf(path_buf, sizeof(path_buf), "%s/%s", g_log_path, g_log_file);
    fp = fopen(path_buf, "a+");
    if (NULL == fp) {
        perror(path_buf);
        abort();
    }
    
    tm = time(NULL);
    //write head info first
    fprintf(fp, "[%.24s] %s\n", ctime(&tm), msg);
    fflush(fp);
}

